package cn.wolfcode.trip.core.service.impl;

import cn.wolfcode.trip.core.domain.StrategyContent;
import cn.wolfcode.trip.core.domain.StrategyDetail;
import cn.wolfcode.trip.core.mapper.StrategyContentMapper;
import cn.wolfcode.trip.core.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.core.query.QueryObject;
import cn.wolfcode.trip.core.service.IStrategyDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService {

    @Autowired
    private StrategyDetailMapper strategyDetailMapper;

    @Autowired
    private StrategyContentMapper contentMapper;

    @Override
    public void saveOrUpdate(StrategyDetail strategyDetail) {
        // 判断是否是发布状态，如果是就设置发布时间
        if(strategyDetail.getState()==StrategyDetail.STATE_RELEASE){
            strategyDetail.setReleaseTime(new Date());
        }
        // 判断用户是否填了序号，没有填就自增1
        if(strategyDetail.getSequence()==null){
            // 根据大攻略id查询最大的序号
            int max = strategyDetailMapper.selectMaxSequenceByCatalogId(strategyDetail.getCatalog().getId());
            strategyDetail.setSequence(max+1);
        }
        if(strategyDetail.getId()!=null){
            strategyDetailMapper.updateByPrimaryKey(strategyDetail);
            // 再保存攻略内容表
            StrategyContent strategyContent = strategyDetail.getStrategyContent();
            strategyContent.setId(strategyDetail.getId());
            contentMapper.updateByPrimaryKey(strategyContent);
        }else{
            // 先保存文章表
            strategyDetailMapper.insert(strategyDetail);
            // 再保存攻略内容表
            StrategyContent strategyContent = strategyDetail.getStrategyContent();
            strategyContent.setId(strategyDetail.getId());
            contentMapper.insert(strategyContent);
        }
    }

    public StrategyContent getContentById(Long id) {
        return contentMapper.selectByPrimaryKey(id);
    }

    public StrategyDetail getById(Long id) {
        return strategyDetailMapper.selectByPrimaryKey(id);
    }


    @Override
    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<StrategyDetail> list = strategyDetailMapper.selectForList(qo);
        return new PageInfo(list);
    }

}
